package com.zjh.simpledao.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zjh
 * @version V1.0.0
 * @date 2019/2/21 14:09
 * @since 1.0
 */
public class StringUtils {
  private static Pattern linePattern = Pattern.compile("_(\\w)");

  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }

  public static boolean isNotEmpty(String str) {
    return !isEmpty(str);
  }
  /**
   * 下划线转驼峰
   *
   * @param str
   * @return
   */
  public static String lineToHump(String str) {
    if (null == str || "".equals(str)) {
      return str;
    }
    str = str.toLowerCase();
    Matcher matcher = linePattern.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
      matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
    }
    matcher.appendTail(sb);
    str = sb.toString();
    return str;
  }

  public static String join(Collection collection, String separator) {
    return collection == null ? null : join(collection.iterator(), separator);
  }

  public static String toString(Object obj) {
    return obj == null ? "" : obj.toString();
  }

  public static String join(Iterator iterator, String separator) {
    if (iterator == null) {
      return null;
    } else if (!iterator.hasNext()) {
      return "";
    } else {
      Object first = iterator.next();
      if (!iterator.hasNext()) {
        return toString(first);
      } else {
        StringBuffer buf = new StringBuffer(256);
        if (first != null) {
          buf.append(first);
        }

        while (iterator.hasNext()) {
          if (separator != null) {
            buf.append(separator);
          }

          Object obj = iterator.next();
          if (obj != null) {
            buf.append(obj);
          }
        }
        return buf.toString();
      }
    }
  }
  /**
   * 首字母转小写
   *
   * @param s
   * @return
   */
  public static String toLowerCaseFirstOne(String s) {
    if (StringUtils.isEmpty(s)) {
      return s;
    }
    if (Character.isLowerCase(s.charAt(0))) {
      return s;
    } else {
      return (new StringBuilder())
          .append(Character.toLowerCase(s.charAt(0)))
          .append(s.substring(1))
          .toString();
    }
  }

  /**
   * 首字母转大写
   *
   * @param s
   * @return
   */
  public static String toUpperCaseFirstOne(String s) {
    if (StringUtils.isEmpty(s)) {
      return s;
    }
    if (Character.isUpperCase(s.charAt(0))) {
      return s;
    } else {
      return (new StringBuffer())
          .append(Character.toUpperCase(s.charAt(0)))
          .append(s.substring(1))
          .toString();
    }
  }
}
